<template>
    <div id="createNewLesson" class="flex-center">
        <div class="create-containter">
            <div class="title">
                <div>
                    <span>创建课程目录</span>
                </div>
                <img class="colse pointer" src="./img/close.png" alt="" @click="close" />
            </div>
            <div class="create_content">
                <div class="theme_Wapper">
                    <div style="font-size: 18px;color: #303133;margin-bottom: 15px;">课程主题管理</div>
                    <div class="theme_content">
                        <div class="theme_box">
                            <div v-for="(item , index) in userThemeData"  class="theme_items" :key="item.id">
                                <div @click="themeChange(item)"  :class="[currentThemeId == item.id ? 'activeTheme' : '']">
                                    <el-input type="text"  maxlength="15" ref="themeInput" v-model="item.themeName"  :readonly="item.isReadonly"  class="theme_input" />
                                    <div class="edit_theme_icon"  v-if="item.isReadonly">
                                        <img style="width: 15px;height: 15px;" src="./img/edit_theme.png" alt="" @click.prevent="openEditTheme(item , index)">
                                        <img style="width: 16px;height: 16px;margin-left: 15px;" src="./img/delete_theme.png" alt="" @click="deleteTheme(item)">
                                    </div>
                                    <div v-if="!item.isReadonly" class="add_btn" @click="editTheme(item , index)"><img src="./img/addBtn.png" alt=""></div>
                                </div>
                            </div>
                        </div>
                        <div class="add_theme_input" :class="[userThemeData.length > 0 ? 'mt20' : '']" v-if="showCreateNewTheme">
                            <el-input type="text" maxlength="15" v-model="newThemeName" ref="new_themeInput" class="theme_input" />
                            <div class="add_btn" @click="addTheme"><img src="./img/addBtn.png" alt=""></div>
                        </div>
                    </div>
                    <div class="add_theme_text" :class="[userThemeData.length > 0 || showCreateNewTheme ? 'mt20' : '']" @click="openCreatNewTheme">
                        +  添加主题
                    </div>
                </div>
                <div class="midline"></div>
                <div class="lesson_Wapper">
                    <div style="font-size: 18px;color: #303133;margin-bottom: 15px;">课程章节管理</div>
                    <div class="lesson_content">
                        <div class="lesson_box">
                            <div v-for="(item , index) in userLessonData"  class="lesson_items"  :key="item.id">
                                <div >
                                    <el-input type="text" maxlength="15" ref="lessonInput" v-model="item.lessonName"  :readonly="item.isReadonly"  class="theme_input" />
                                    <div class="edit_lesson_icon"  v-if="item.isReadonly">
                                        <img style="width: 15px;height: 15px;" src="./img/edit_theme.png" alt="" @click="openEditLesson(item , index)">
                                        <img style="width: 16px;height: 16px;margin-left: 15px;" src="./img/delete_theme.png" alt="" @click="deleteLesson(item)">
                                    </div>
                                    <div v-if="!item.isReadonly" class="add_btn" @click="editLesson(item , index)"><img src="./img/addBtn.png" alt=""></div>
                                </div>
                            </div>
                        </div>
                        <div class="add_lesson_input" v-if="showCreateNewLesson">
                            <el-input type="text" maxlength="15" v-model="newLessonName" ref="new_lessonInput" class="theme_input" />
                            <div class="add_btn" @click="addLesson"><img src="./img/addBtn.png" alt=""></div>
                        </div>
                    </div>
                    <div  class="add_lesson_text" :class="[showCreateNewLesson ? 'mt20' : '']" @click="openCreatNewLesson">
                        +  添加课程
                    </div>
                </div>
            </div>
            <div class="saveBtn" @click="save">
                保存
            </div>
        </div>
        
    </div>
</template>
<script>
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib'
import { SqlLibBook } from '../../../../../../static/lib/sqlite/service/SqlLibBook'
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser'
import { Book } from '../../../../../../static/lib/sqlite/model/Book'
import { Chapter } from '../../../../../../static/lib/sqlite/model/Chapter'
import { Lesson } from '../../../../../../static/lib/sqlite/model/Lesson'
import usermeta from '../../../api/usermeta.js'
import { FileUtil } from '../../../../../../static/utils/FileUtil'
import bus from  '../../../assets/js/bus.js'
export default {
    name:'',
    components: {},
    data() {
        return {
            userThemeData:[],
            userLessonData:[],
            showCreateNewTheme:false,
            showCreateNewLesson:false,
            newThemeName:'',
            newLessonName:'',
            activeManage:0,
            currentThemeId:'',
            LessonsData:[],
            isNeedUpdata:false,
        };
    },
    computed: {},
    watch: {},
    methods: {
        save(){
            bus.$emit('colseCreateLesson',this.isNeedUpdata)
        },
        openCreatNewLesson(){
            if (this.userThemeData.length == 0) {
                this.$message.warning('请先您创建主题')
                return
            }
            this.showCreateNewLesson = true 
            this.$nextTick(() =>{
                this.$refs.new_lessonInput.focus()
            });
        },
        addLesson(){
            if (this.newLessonName == '') {
                this.$message.warning('请输入课程名称')
                return
            }
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            console.log('userLessonData',this.userLessonData);
            usermeta.createUserDiyLesson({
                id:this.currentThemeId,
                name:this.newLessonName,
                sortIndex:this.userLessonData.length,
            }).then(res=>{
                console.log('rsss', res);
                if (res.code == '0') {
                    this.isNeedUpdata = true
                    this.$message.success('创建成功')
                    this.showCreateNewLesson = false
                    let lesson = new Lesson()
                    lesson.id = res.returnValue.id
                    lesson.name = res.returnValue.name
                    lesson.chapterId = res.returnValue.userDiySubjectId
                    lesson.isCharged = '1'
                    lesson.reverse3 = 'userDiy'
                    console.log('lesson',lesson);
                    sqlLib.updateOrInsertObjectById(lesson)
                    this.newLessonName = ''
                }else{
                    this.$message.warning(res.message)
                }
                this.getDiyLessons()
            })
        },
        //删除某一课的本地课程资源
        deleteLocalRes(lessonId){
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let user = SqlLibUser.queryCurrentUser(sqlLib)
            let lessonResource = SqlLibUser.queryLessonResource(sqlLib, user.id, lessonId)
            console.log(lessonResource);
            //删除自上传资源
            const path = require('path')
            const fs = require('fs')
            lessonResource.forEach(resource=>{
                switch (resource.resourceType) {
                   //课件
                    case 'selfPpt':
                        FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'ppt', user.id, resource.resourceName))
                        break;
                        //视频
                    case 'selfVideo':
                        let videoPath = path.resolve(window.$DATADIR, 'resc', 'selfVideo',resource.resourceName)
                        if (fs.existsSync(videoPath)) {
                            FileUtil.deleteFile(videoPath)
                        }else{
                            FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'video', user.id, resource.resourceName))
                        }
                        break;
                        //图片
                    case 'selfImg':
                        let imgPath = path.resolve(window.$DATADIR, 'resc', 'selfImg',resource.resourceName)
                        console.log(imgPath);
                        if (fs.existsSync(imgPath)) {
                            FileUtil.deleteFile(imgPath)
                        }else{
                            FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'img', user.id, resource.resourceName))
                        }
                        break;
                        //pdf文件
                    case 'selfPdf':
                        let pdfPath = path.resolve(window.$DATADIR, 'resc', 'selfPdf',resource.resourceName)
                        if (fs.existsSync(pdfPath)) {
                            FileUtil.deleteFile(pdfPath)
                        }else{
                            FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'pdf', user.id, resource.resourceName))
                        }
                        break;
                        //word文件
                    case 'selfWord':
                        let wordPath = path.resolve(window.$DATADIR, 'resc', 'selfWord',resource.resourceName)
                        if (fs.existsSync(wordPath)) {
                            FileUtil.deleteFile(wordPath)
                        }else{
                            FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'word', user.id, resource.resourceName))
                        }
                        break;
                        //音频
                    case 'selfAudio':
                        let audioPath = path.resolve(window.$DATADIR, 'resc', 'selfAudio',resource.resourceName)
                        if (fs.existsSync(audioPath)) {
                            FileUtil.deleteFile(audioPath)
                        }else{
                            FileUtil.deleteFile(path.resolve(window.$DATADIR, 'resc', 'user', 'audio', user.id, resource.resourceName))
                        }
                        break;
                    default:
                        break;
                }
            })
            let param = {
                lessonId:lessonId
            }
            //删除课程资源
            SqlLibBook.deleteAllLessonInfoByBookId(sqlLib,param)
        },
        deleteLesson(row){
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            console.log(row);
            // return
            this.$dialog({
                confirm: '确认',
                cancel: '取消',
                message: '确定删除该课程',
                close: false,
                type: 'warn',
                title:'温馨提示'
            }).then(()=>{
                
                usermeta.delUserDiyLesson({
                    id:row.id,
                }).then(res=>{
                    if (res.code == '0') {
                        this.isNeedUpdata = true
                        this.$message.success('删除成功')
                        let lesson = new Lesson()
                        lesson.id = row.id
                        sqlLib.deleteObjectById(lesson)
                        this.deleteLocalRes(row.id)
                        this.getDiyLessons()
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            }).catch(()=>{
            })
        },
        openEditLesson(row , index){
            row.isReadonly = false
            this.$nextTick(() =>{
                this.$refs.lessonInput[index].focus()
            });
        },
        editLesson(row , index){
            var isChange = false
            this.LessonsData.forEach(item=>{
                if (item.subjectId == this.currentThemeId) {
                    item.userDiyLessonVOList.forEach(val=>{
                        if (row.id == val.lessonId) {
                            if (row.lessonName == val.name) {
                                console.log('没改');
                            }else{
                                isChange = true
                            }
                        }
                    })
                }
            })
            if (isChange) {
                usermeta.editUserDiyLesson({
                    name:row.lessonName,
                    id:row.id,
                }).then(res=>{
                    console.log(res);
                    if (res.code == '0') {
                        this.$message.success('编辑成功')
                        this.isNeedUpdata = true
                        row.isReadonly = true
                        let lesson = new Lesson()
                        lesson.id = row.id
                        let currentLesson = SqlLib.getInstance(window.$DBDIR).selectObjectById(lesson)
                        currentLesson.name = row.lessonName
                        console.log('currentLesson',currentLesson);
                        SqlLib.getInstance(window.$DBDIR).updateObjectById(currentLesson)
                    }
                })
            }
                
        },
        themeChange(item){
            this.currentThemeId = item.id
            this.getDiyLessons()
        },
        openCreatNewTheme(){
            this.showCreateNewTheme = true 
            this.$nextTick(() =>{
                this.$refs.new_themeInput.focus()
            });
        },
        addTheme(){
            event.stopPropagation();
            if (this.newThemeName == '') {
                this.$message.warning('请输入主题名称')
                return
            }
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            usermeta.createUserSubject({
                name:this.newThemeName,
                sortIndex:this.userThemeData.length ,
            }).then(res=>{
                console.log('rsss', res);
                if (res.code == '0') {
                    this.isNeedUpdata = true
                    this.$message.success('创建成功')
                    this.showCreateNewTheme = false
                    let chapter = new Chapter()
                    chapter.id = res.returnValue.id
                    chapter.name = res.returnValue.name
                    chapter.bookId = res.returnValue.userId
                    console.log('chapter',chapter);
                    sqlLib.updateOrInsertObjectById(chapter)
                    this.newThemeName = ''
                }else{
                    this.$message.warning(res.message)
                }
                this.getDiyLessons()
            })
        },
        deleteTheme(row){
            this.$dialog({
                confirm: '确认',
                cancel: '取消',
                message: '该主题下的课程将被删除',
                close: false,
                type: 'warn',
                title:'温馨提示'
            }).then(()=>{
                let sqlLib = SqlLib.getInstance(window.$DBDIR)
                usermeta.delUserSubject({
                    id:row.id,//删除的主题id
                }).then(res=>{
                    if (res.code == '0') {
                        this.isNeedUpdata = true
                        this.$message.success('删除成功')
                        let chapter = new Chapter()
                        chapter.id = row.id
                        sqlLib.deleteObjectById(chapter)
                        console.log(this.LessonsData);
                        this.LessonsData.forEach(item=>{
                            if (item.subjectId == row.id) {
                                item.userDiyLessonVOList.forEach(val=>{
                                    this.deleteLocalRes(val.lessonId)
                                    let lesson = new Lesson()
                                    lesson.id = val.lessonId
                                    sqlLib.deleteObjectById(lesson)
                                })
                            }
                        })
                        this.getDiyLessons()
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            }).catch(()=>{
            })
        },
        openEditTheme(row , index){
            event.stopPropagation();
            row.isReadonly = false
            //this.$refs.editTheme.onfocus();	 无效
            //原因在于data中的数据发生变化后，vue的依赖监听并更新视图过程是异步进行的，所以此时视图更新任务还在等待，输入框并没有渲染出来，此时通过$refs操作dom是无效的。
            console.log(this.$refs.themeInput[index]);
            this.$nextTick(() =>{
                this.$refs.themeInput[index].focus()
            });
        },
        editTheme(row , index){
            console.log(row);
            var isChange = false
            this.LessonsData.forEach(item=>{
                if (item.subjectId == this.currentThemeId) {
                    if (row.themeName == item.name) {
                        console.log('没改');
                    }else{
                        isChange = true
                    }
                }
            })
            if (isChange) {
                usermeta.editUserSubject({
                    id:row.id,
                    name:row.themeName,
                }).then(res=>{
                    console.log(res);
                    if (res.code == '0') {
                        this.$message.success('编辑成功')
                        this.isNeedUpdata = true
                        let chapter = new Chapter()
                        chapter.id = row.id
                        let currentSubject = SqlLib.getInstance(window.$DBDIR).selectObjectById(chapter)
                        currentSubject = row.themeName
                        SqlLib.getInstance(window.$DBDIR).updateObjectById(currentSubject)
                    }
                })
            }
        },
        close(){
            bus.$emit('colseCreateLesson',this.isNeedUpdata)
        },
        changeSort(row,msg){
            if (this.userThemeData.length == 1) {
                return
            }
            this.userThemeData.forEach((item,index)=>{
                if (msg == 'up'){//上移
                    if (item.id == row.id) {
                        if (index == 0) {//上移第一条数据
                            console.log('第一条数据');
                            return
                            // item.sortIndex = this.userThemeData[this.userThemeData.length -1].sortIndex+1
                        }else{
                            let tampIndex  = this.userThemeData[index -1].sortIndex
                            this.userThemeData[index -1].sortIndex = item.sortIndex
                            item.sortIndex = tampIndex
                        }
                    }
                }else if(msg == 'down'){
                    if (index == this.userThemeData.length -1) {
                        console.log('最后一条数据');
                        return
                    }
                    if (item.id == row.id) {
                        let tampIndex  = this.userThemeData[index +1].sortIndex
                        this.userThemeData[index +1].sortIndex = item.sortIndex
                        item.sortIndex = tampIndex
                    }
                }
            })
            // return
            console.log(this.userThemeData);
            usermeta.editUserSubject({
                userSubjectJson:JSON.stringify(this.userThemeData)
            }).then(res=>{
                if (res.code == '0') {
                    this.getDiyLessons()
                }
            })
        },
        getDiyLessons(){
            usermeta.getAllDiyLessons({}).then(res=>{
                if (res.code == '0') {
                    this.userThemeData = []
                    this.userLessonData = []
                    if (res.returnValue == []) {
                        return
                    }
                    if (res.returnValue) {
                        this.LessonsData = res.returnValue
                        if (!this.currentThemeId) {
                            this.currentThemeId = res.returnValue[0].subjectId
                        }
                    }
                    res.returnValue.forEach((item,index)=>{
                        this.userThemeData.push({
                            themeName:item.name,
                            id:item.subjectId,
                            sortIndex:item.sortIndex,
                            isReadonly:true,
                        })
                        if (this.currentThemeId == item.subjectId) {
                            if (item.userDiyLessonVOList) {
                                item.userDiyLessonVOList.forEach(val=>{
                                    this.userLessonData.push({
                                        lessonName:val.name,
                                        id:val.lessonId,
                                        sortIndex:val.sortIndex,
                                        isReadonly:true,
                                    })
                                })
                            }
                        }
                        
                    })
                }
                this.userThemeData = this.userThemeData.sort(this.compare('sortIndex'))
                console.log(this.userThemeData);
                console.log(res);
            })
        },
        //比较排序
        compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
            }
        },
    },
    created() {
    
    },
    mounted() {
        this.getDiyLessons('initTheme')
    },
}
</script>
<style scoped lang="scss">
::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: transparent !important;
}
::-webkit-scrollbar {
    width: 4px;
    background: transparent !important;
    // background: red !important;
    /*height: 4px;*/
}
#createNewLesson{
    position: fixed;
    background: rgba(0, 0, 0, 0.7);
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 9999!important;
    
    .create-containter {
        width:880px;
        height: 560px;
        border-radius: 4px;
        position: relative;
        // background-color: #fff;
        box-sizing: border-box;
        background-image: url("./img/changePublishBg.png");
        background-repeat: no-repeat;
        background-size: cover;
        .saveBtn{
            width: 120px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #FFFFFF;
            font-weight: bold;
            background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            left: calc(50% - 60px);
            bottom: 20px;
        }
        .title{
            border-radius: 8px 8px 0 0;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0  18px;
            height: 48px;
            color: #303133;
            font-weight: bold;
            .colse{
                position: absolute;
                right: 23px;
                width: 11px;
                height: 12px;
            }
        }
        
        .create_content{
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }
        .theme_Wapper{
            width: 440px;
            padding: 0 38px;
            position: relative;
            box-sizing: border-box;
            .theme_content{
                overflow-y: scroll;
                max-height: 320px;
                .theme_box{
                    .theme_items{
                        position: relative;
                        margin-bottom: 20px;
                        width: 360px;
                        height: 40px;
                        border-radius: 4px;
                        border: 1px solid #0085FF;
                        color: #0085FF;
                        .edit_theme_icon{
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            height: 38px;
                            width: 70px;
                            position: absolute;
                            top: 0;
                            right: 0;
                            img{
                                z-index: 99;
                                cursor: pointer;
                            }
                        }
                        .add_btn{
                            width: 40px;
                            height: 38px;
                            background: #0085FF;
                            border-radius: 0px 4px 4px 0px;
                            cursor: pointer;
                            position: absolute;
                            top: 0;
                            right: -1px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            img{
                                width: 18px;
                                height: 13px;
                            }
                        }
                    }
                    .theme_items:last-child{
                        margin-bottom: 0px;
                    }
                }
                .add_theme_input{
                    position: relative;
                    cursor: pointer;
                    line-height: 36px;
                    width: 360px;
                    height: 40px;
                    background: #FFFFFF;
                    border-radius: 4px;
                    border: 1px solid #0085FF;
                    color: #0085FF;
                    .add_btn{
                        width: 40px;
                        height: 38px;
                        background: #0085FF;
                        border-radius: 0px 4px 4px 0px;
                        cursor: pointer;
                        position: absolute;
                        top: 0;
                        right: -1px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        img{
                            width: 18px;
                            height: 13px;
                        }
                    }
                }
            }
            .add_theme_text{
                cursor: pointer;
                line-height: 36px;
                width: 360px;
                height: 40px;
                background: #FFFFFF;
                border-radius: 4px;
                border: 1px solid #0085FF;
                color: #0085FF;
                text-align: center;
            }
        }
        .midline{
            position: absolute;
            margin-top: 20px;
            height: 372px;
            border-right: 2px dashed #DEE2E6;
        }
        .lesson_Wapper{
            width: 440px;
            padding: 0 38px;
            position: relative;
            box-sizing: border-box;
            .lesson_content{
                overflow-y: scroll;
                max-height: 320px;
                .lesson_box{
                    .lesson_items{
                        margin-bottom: 20px !important;
                        position: relative;
                        width: 360px;
                        height: 40px;
                        border-radius: 4px;
                        border: 1px solid #0085FF;
                        color: #0085FF;
                        .edit_lesson_icon{
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            height: 38px;
                            width: 70px;
                            position: absolute;
                            top: 0;
                            right: 0;
                            img{
                                cursor: pointer;
                            }
                        }
                        .add_btn{
                            width: 40px;
                            height: 38px;
                            background: #0085FF;
                            border-radius: 0px 4px 4px 0px;
                            cursor: pointer;
                            position: absolute;
                            top: 0;
                            right: -1px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            img{
                                width: 18px;
                                height: 13px;
                            }
                        }
                    }
                    .lesson_items:last-child{
                        margin-bottom: 0px;
                    }
                }
                .add_lesson_input{
                    position: relative;
                    cursor: pointer;
                    line-height: 36px;
                    width: 360px;
                    height: 40px;
                    background: #FFFFFF;
                    border-radius: 4px;
                    border: 1px solid #0085FF;
                    color: #0085FF;
                    // text-align: center;
                    .newLesson{
                        width: 320px;
                        height: 36px;
                    }
                    .add_btn{
                        width: 40px;
                        height: 38px;
                        background: #0085FF;
                        border-radius: 0px 4px 4px 0px;
                        cursor: pointer;
                        position: absolute;
                        top: 0;
                        right: -1px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        img{
                            width: 18px;
                            height: 13px;
                        }
                    }
                }
            }
            .add_lesson_text{
                cursor: pointer;
                line-height: 36px;
                width: 360px;
                height: 40px;
                background: #FFFFFF;
                border-radius: 4px;
                border: 1px solid #0085FF;
                color: #0085FF;
                text-align: center;
            }
        }
        .mt20{
            margin-top: 20px;
        }
        .activeTheme{
            background: rgba(0,133,255,0.1);
        }
    }
}
</style>

<style lang="scss" scope>
.theme_input{
    .el-input__inner{
        background-color: transparent;
        border: none;
        height: 38px;
        color: #303133;
        font-size: 16px;
    }
}
</style>